Skip to content

[ENG-603] Fix caching in care backend build actions#3696

Open
tellmeY18 wants to merge 5 commits into
ohcnetwork:developfrom
tellmeY18:fix/workflow-cache
Open

[ENG-603] Fix caching in care backend build actions#3696
tellmeY18 wants to merge 5 commits into
ohcnetwork:developfrom
tellmeY18:fix/workflow-cache

Conversation

@tellmeY18

@tellmeY18 tellmeY18 commented Jun 26, 2026

Copy link
Copy Markdown
Member

Proposed Changes

  • Replace GHA filesystem cache (actions/cache) with native BuildKit registry cache backed by GHCR (type=registry) in both deploy.yml and reusable-test.yml
  • Remove reproducible-containers/buildkit-cache-dance third-party action dependency
  • Add resolve_plugins.py script to resolve plugin branch refs to commit SHAs via git ls-remote and produce a deterministic cache-busting hash as a Docker build arg (PLUGIN_RESOLVED_HASH)
  • Add prune-cache job to delete buildcache-* GHCR package versions older than 4 weeks after each successful develop push
  • Fix --cache-to on fork PRs (skipped on pull_request events to avoid GHCR auth failures)

Associated Issue

ENG-603

Summary by CodeRabbit

  • New Features
    • Improved build and test workflows to use registry-backed Docker Buildx caching for faster repeat runs.
    • Added deterministic plugin cache-busting during image builds based on resolved plugin versions.
  • Bug Fixes
    • Added robust handling for missing/invalid plugin configuration, including clear success/failure behavior.
  • Chores
    • Added automatic pruning of old build-cache artifacts on the appropriate branch to keep registry storage tidy.

@tellmeY18 tellmeY18 requested a review from a team as a code owner June 26, 2026 09:48
@coderabbitai

coderabbitai Bot commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 62e2e0b5-380e-41a3-84dc-f5d8b0faa5b5

📥 Commits

Reviewing files that changed from the base of the PR and between ba2e22f and 7faf1f7.

📒 Files selected for processing (4)
  • .github/scripts/resolve_plugins.py
  • .github/workflows/reusable-test.yml
  • docker/dev.Dockerfile
  • docker/prod.Dockerfile
🚧 Files skipped from review as they are similar to previous changes (3)
  • .github/scripts/resolve_plugins.py
  • docker/dev.Dockerfile
  • .github/workflows/reusable-test.yml

📝 Walkthrough

Walkthrough

Adds a plugin-hash resolver, switches reusable-test and deploy builds to GHCR-backed Buildx caches, passes the resolved hash into Docker builds, and adds a deploy job that deletes older GHCR build cache versions.

Changes

Build cache and plugin hash plumbing

Layer / File(s) Summary
Plugin hash resolver
.github/scripts/resolve_plugins.py
ADDITIONAL_PLUGS is parsed as JSON, invalid or empty values emit no-plugins, missing package_name fails, @ versions are resolved through git ls-remote, and a deterministic short hash is printed.
Registry-backed build cache
.github/workflows/reusable-test.yml, .github/workflows/deploy.yml, docker/dev.Dockerfile, docker/prod.Dockerfile
The build workflows compute weekly cache tags and a plugin hash, switch Buildx cache settings to GHCR registry references, pass PLUGIN_RESOLVED_HASH and ADDITIONAL_PLUGS into Docker builds, and remove the local cache move/save steps.
Cache pruning job
.github/workflows/deploy.yml
prune-cache lists GHCR package versions, filters buildcache-* tags older than the weekly cutoff, and deletes matching versions with gh api.

Estimated code review effort: 3 (Moderate) | ~25 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main change: fixing build cache behavior.
Description check ✅ Passed It includes proposed changes and the associated issue, with only the merge checklist left out.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands.

…n staleness mitigation

- Replace actions/cache + local buildx cache with type=registry GHCR cache
- Use weekly-rotated cache tags (buildcache-{platform}-{year-Wweek})
- Add prune-cache job to delete tags older than 4 weeks on develop
- Add resolve_plugins.py to compute PLUGIN_RESOLVED_HASH from @Branch refs
  for cache busting when plugin upstreams change
- Add PLUGIN_RESOLVED_HASH ARG/ENV to both Dockerfiles
- Remove buildkit-cache-dance and all GHA cache boilerplate from test workflow
- Conditional cache-to in reusable-test.yml (write only on push)
@tellmeY18 tellmeY18 force-pushed the fix/workflow-cache branch from 9c55d2e to 9d9a3ea Compare June 26, 2026 09:50
@greptile-apps

greptile-apps Bot commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR replaces filesystem-based actions/cache with BuildKit registry cache backed by GHCR, removes the reproducible-containers/buildkit-cache-dance dependency, adds a resolve_plugins.py script for deterministic plugin cache-busting, and introduces a prune-cache job to clean up old buildcache-* GHCR tags.

  • resolve_plugins.py: resolves plugin branch refs to commit SHAs via git ls-remote and emits a 16-char SHA-256 hash used as PLUGIN_RESOLVED_HASH build arg; fallback handling on network errors is now visible via stderr.
  • deploy.yml: prod build correctly sets cache-to unconditionally (safe since the workflow only runs on push/tags/workflow_dispatch where GHCR auth is always available); prune-cache job lexicographically compares ISO week strings to identify stale versions.
  • reusable-test.yml: registry cache login and cache tag computation are correct, but the CACHE_TO write guard uses github.event_name which is always \"workflow_call\" in a reusable workflow, causing the dev cache to never be written.

Confidence Score: 4/5

Safe to merge for the prod build path; the dev build cache write is broken but does not affect CI correctness, only cache effectiveness.

The reusable-test.yml CACHE_TO write guard checks github.event_name which is always workflow_call in a reusable workflow, meaning the dev build cache is never populated in the registry. Every push to develop reads from but never refreshes the cache, leaving it permanently stale after the first cold miss.

reusable-test.yml — the CACHE_TO write guard on line 47 needs to reference inputs.event_name instead of (or in addition to) github.event_name.

Important Files Changed

Filename Overview
.github/scripts/resolve_plugins.py New script to resolve plugin branch refs to commit SHAs and produce a deterministic cache-busting hash; logic is sound, exception handling and fallbacks are reasonable.
.github/workflows/deploy.yml Switches prod build to registry-backed BuildKit cache; adds prune-cache job and plugin hash build arg; cache-to always set but deploy.yml only runs on push/tags/workflow_dispatch where GHCR auth is available, so no auth-failure risk.
.github/workflows/reusable-test.yml Switches dev build to registry-backed cache, but the CACHE_TO conditional uses github.event_name (always "workflow_call" in reusable workflows) instead of inputs.event_name, so the cache is never written — defeating the purpose.
docker/dev.Dockerfile Adds PLUGIN_RESOLVED_HASH ARG before the plugin-install RUN layer; ARG placement correctly triggers Docker layer-cache invalidation when the hash changes.
docker/prod.Dockerfile Same PLUGIN_RESOLVED_HASH pattern applied correctly; no issues found.

Reviews (4): Last reviewed commit: "Address review comments on plugin cache ..." | Re-trigger Greptile

Comment thread .github/scripts/resolve_plugins.py Outdated
Comment thread .github/workflows/reusable-test.yml Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
.github/workflows/reusable-test.yml (1)

24-29: 🔒 Security & Privacy | 🔵 Trivial | 💤 Low value

Optional: unpinned docker/login-action@v3.

zizmor flags Line 25 as unpinned per a blanket-hash policy. It's consistent with the rest of this workflow's tag-pinned actions, so this is only worth addressing if you intend to enforce SHA pinning repo-wide.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.github/workflows/reusable-test.yml around lines 24 - 29, The GitHub
Container Registry login step uses an action pinned only by tag, which may
violate the repo’s SHA-pin policy. If this workflow should follow the same
enforcement as the other tag-pinned actions, update the Docker login step in the
reusable test workflow to use a fixed commit SHA for docker/login-action instead
of `@v3`, keeping the existing Login to GitHub Container Registry block and its
inputs unchanged.

Source: Linters/SAST tools

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.github/scripts/resolve_plugins.py:
- Around line 26-42: The plugin ref resolution in resolve_plugins.py is silently
falling back to the raw branch/ref when git ls-remote fails or returns no
output, which makes values like pkg@main stop changing and hides resolution
problems; update the logic around the ref handling to surface the failure
instead of assigning sha from ref. Also fix the version defaulting in the
package version lookup so a null version is treated like missing input by using
the same default path as the versionless case, and make sure the
ver.startswith("@") branch in the resolver no longer crashes on null values.

In @.github/workflows/reusable-test.yml:
- Around line 42-54: The build step in the reusable workflow is passing
ADDITIONAL_PLUGS directly from the GitHub expression into the shell, which can
strip JSON quotes and split the value before docker buildx receives it. Move
ADDITIONAL_PLUGS into the step env and reference it as a quoted shell variable
in the Build images run block, using the existing docker buildx build invocation
and keeping PLUGIN_RESOLVED_HASH unchanged.

In `@docker/prod.Dockerfile`:
- Around line 37-40: The builder-stage plugin install step in
docker/prod.Dockerfile is not using PLUGIN_RESOLVED_HASH, so changes to the
resolved plugin set do not invalidate the install_plugins.py layer. Update the
RUN step that invokes install_plugins.py to reference PLUGIN_RESOLVED_HASH
alongside the existing ARGs, using the same pattern as the corresponding
dev.Dockerfile cache-busting fix, so the layer is rebuilt whenever the hash
changes.

---

Nitpick comments:
In @.github/workflows/reusable-test.yml:
- Around line 24-29: The GitHub Container Registry login step uses an action
pinned only by tag, which may violate the repo’s SHA-pin policy. If this
workflow should follow the same enforcement as the other tag-pinned actions,
update the Docker login step in the reusable test workflow to use a fixed commit
SHA for docker/login-action instead of `@v3`, keeping the existing Login to GitHub
Container Registry block and its inputs unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 8740dfbc-e1d4-4a9b-896b-a767c37f5131

📥 Commits

Reviewing files that changed from the base of the PR and between c8baced and 9d9a3ea.

📒 Files selected for processing (5)
  • .github/scripts/resolve_plugins.py
  • .github/workflows/deploy.yml
  • .github/workflows/reusable-test.yml
  • docker/dev.Dockerfile
  • docker/prod.Dockerfile

Comment on lines +26 to +42
if ver.startswith("@"):
ref = ver[1:]
git_url = pkg.removeprefix("git+")
try:
out = subprocess.run( # noqa: S603
["git", "ls-remote", git_url, ref], # noqa: S607
check=False,
capture_output=True,
text=True,
timeout=15,
)
sha = out.stdout.split()[0] if out.stdout else ref
except Exception:
sha = ref
resolved.append(f"{pkg}@{sha}")
else:
resolved.append(f"{pkg}{ver}")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

python3 - <<'PY'
from pathlib import Path
p = Path('.github/scripts/resolve_plugins.py')
print(p.exists(), p)
print(p.read_text())
PY

Repository: ohcnetwork/care

Length of output: 1395


🏁 Script executed:

python3 - <<'PY'
from pathlib import Path
p = Path('.github/scripts/resolve_plugins.py')
print(p.exists(), p)
print(p.read_text())
PY

Repository: ohcnetwork/care

Length of output: 1395


Avoid falling back to the raw ref here. When git ls-remote fails or returns nothing, sha becomes ref, so @main hashes like pkg@main and stops busting the cache when the branch moves. Surface the failure instead of quietly pretending it resolved.

Also, p.get("version", "@main") does not cover "version": null; that still reaches ver.startswith("@") and crashes. Use p.get("version") or "@main" if null should mean default.

🧰 Tools
🪛 ast-grep (0.44.0)

[error] 29-35: Command coming from incoming request
Context: subprocess.run( # noqa: S603
["git", "ls-remote", git_url, ref], # noqa: S607
check=False,
capture_output=True,
text=True,
timeout=15,
)
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').

(subprocess-from-request)

🪛 Ruff (0.15.18)

[warning] 38-38: Do not catch blind exception: Exception

(BLE001)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.github/scripts/resolve_plugins.py around lines 26 - 42, The plugin ref
resolution in resolve_plugins.py is silently falling back to the raw branch/ref
when git ls-remote fails or returns no output, which makes values like pkg@main
stop changing and hides resolution problems; update the logic around the ref
handling to surface the failure instead of assigning sha from ref. Also fix the
version defaulting in the package version lookup so a null version is treated
like missing input by using the same default path as the versionless case, and
make sure the ver.startswith("@") branch in the resolver no longer crashes on
null values.

Source: Linters/SAST tools

Comment thread .github/workflows/reusable-test.yml
Comment thread docker/prod.Dockerfile Outdated
@codecov

codecov Bot commented Jun 26, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 79.66%. Comparing base (c8baced) to head (7faf1f7).
⚠️ Report is 8 commits behind head on develop.

Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #3696      +/-   ##
===========================================
+ Coverage    79.55%   79.66%   +0.10%     
===========================================
  Files          479      479              
  Lines        22996    23010      +14     
  Branches      2378     2379       +1     
===========================================
+ Hits         18295    18330      +35     
+ Misses        4096     4080      -16     
+ Partials       605      600       -5     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ Duplicate comments (1)
.github/scripts/resolve_plugins.py (1)

38-39: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Please fail closed here instead of reusing the ref name.

This still turns a git ls-remote failure into a stable cache key, so branch-based plugins like pkg@main stop invalidating the image cache when the branch moves. Catching broad Exception makes that even easier to miss, which is… convenient in the wrong way. Raise on resolution failure here rather than warning and continuing with the raw ref.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.github/scripts/resolve_plugins.py around lines 38 - 39, The fallback in
resolve_plugins.py should not warn and continue with the raw ref name when git
ls-remote fails, because that creates a stable cache key for moving branches.
Update the exception handling around the git resolution logic to fail closed by
raising on resolution failure instead of returning or reusing the ref name; keep
the change localized near the git_url lookup and the existing except Exception
as exc block.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Duplicate comments:
In @.github/scripts/resolve_plugins.py:
- Around line 38-39: The fallback in resolve_plugins.py should not warn and
continue with the raw ref name when git ls-remote fails, because that creates a
stable cache key for moving branches. Update the exception handling around the
git resolution logic to fail closed by raising on resolution failure instead of
returning or reusing the ref name; keep the change localized near the git_url
lookup and the existing except Exception as exc block.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 513a5f1f-6cf6-43d8-ba6d-5e1a47b3d3d0

📥 Commits

Reviewing files that changed from the base of the PR and between 9d9a3ea and 9a4b733.

📒 Files selected for processing (1)
  • .github/scripts/resolve_plugins.py

@vigneshhari

Copy link
Copy Markdown
Member

@tellmeY18 resolve comments. Lint failing

- Quote ADDITIONAL_PLUGS build-arg to avoid shell word-splitting
- Treat null plugin version as the default @main
- Reference PLUGIN_RESOLVED_HASH in the install step so BuildKit
  invalidates the plugin layer when resolved plugin SHAs change
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants